package com.redpacketcover.rc.base;

/**
 * Created by wangwei on 2019/10/16.
 */


import java.text.ParseException;

import io.reactivex.observers.DisposableObserver;


/**
 * 参考:https://github.com/WuXiaolong/
 * 使用CompositeDisposable   创建一个可被 CompositeDisposable 管理的 observer
 * 防止内存泄漏
 * 对观察者进行封装，实现代码复用和拓展
 */
public abstract class ObserverCallback<T> extends DisposableObserver<BaseResponseBean<T>> {

    public abstract void onSuccess(T model) throws ParseException;

    public abstract void onFailure(int code, String errMsg);


    @Override
    public void onError(Throwable e) {
        e.printStackTrace();
        ApiException baseException = new RxErrorHandler().handleError(e);//网络异常
        BaseResponseBean bean = new BaseResponseBean();
        onFailure(baseException.getCode(), baseException.getMsg());
    }

    @Override
    public void onNext(BaseResponseBean<T> result) {
        int statusCode = result.getCode();
        if (statusCode == 200) {
            try {
                onSuccess(result.getData());
            } catch (ParseException e) {
                e.printStackTrace();
            }
        } else {
            onFailure(result.getCode(), result.getMsg());
        }

    }

    @Override
    public void onComplete() {
    }
}

